<template>
  <ElementDialog :title="title" embed :body-padding="false" :visible="visible" class="msg-history-dialog" width="800px">
    <div class="msg-search-bar">
      <ElInput
        v-model="query"
        class="flex-item"
        placeholder="搜索消息记录"
        prefix-icon="el-icon-search"
        clearable
        size="small"
        style="margin-right: 10px"
        @clear="reload" />
      <ElButton size="small" type="primary" @click="reload">搜索</ElButton>
    </div>
    <div class="msg-search-bar">
      <ElRadioGroup v-model="type" class="icon-render-mode" style="float: right">
        <ElRadioButton label="all">全部</ElRadioButton>
        <ElRadioButton label="image">图片</ElRadioButton>
        <ElRadioButton label="file">文件</ElRadioButton>
      </ElRadioGroup>
    </div>
    <CustomScrollbar ref="scroller" :on-load-more="loadMore" class="msg-history">
      <ul ref="list" class="msg-list" @click="onListClick">
        <li v-for="item in messages" :key="item.id" :data-mid="item.id" class="msg-item">
          <p class="sender-name">{{ item.sender.userId === userId ? '我' : item.sender.name }}</p>
          <div class="msg-item-right">
            <div class="chat-message-content" v-html="parseMsg(item)"></div>
            <p class="send-time">{{ friendlyTime(item.createdAt) }}</p>
          </div>
        </li>
        <li v-if="page.page <= page.pages" class="load-more" @click="loadMore">
          <p v-show="!delay && loading && page.page !== 1" class="load-more-wrapper">
            <i class="el-icon-loading"></i> 加载中...
          </p>
          <p v-show="delay && !loading" class="load-more-wrapper"><i class="el-icon-time"></i> 查看更多...</p>
        </li>
        <li v-else class="load-more">
          <p class="load-more-wrapper"><i class="el-icon-lx-roundcheck"></i> 数据加载完毕！</p>
        </li>
      </ul>
    </CustomScrollbar>
  </ElementDialog>
</template>

<script>
  import { mapState } from 'vuex'
  import { findParent } from '@web-utils/core'
  import { friendlyTime } from '@web-utils/integrations/dayjs'
  import { downloadFile, parseMsg } from '@/components/im/index'
  import { openFile } from '@/api/file-view'
  import { getMessage } from './api/message'

  export default {
    name: 'ChatHistoryDialog',
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      session: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        type: 'all',
        loading: false,
        delay: false,
        messages: [],
        page: { page: 1, limit: 25, pages: 1 },
        query: ''
      }
    },
    computed: {
      ...mapState('user', { userId: state => state.sysUser.userId }),
      title() {
        return `消息记录-${this.session.name ? this.session.name : ''}`
      }
    },
    watch: {
      visible: {
        immediate: true,
        handler(newVal) {
          if (newVal) {
            if (this.$refs.scroller) {
              this.$refs.scroller.viewport.scrollTop = 0
            }
            this.query = ''
            this.reload()
          }
        }
      },
      type() {
        this.reload()
      }
    },
    methods: {
      friendlyTime,
      parseMsg(message) {
        return parseMsg(message)
      },
      async onListClick(event) {
        const target = event.target
        if (target.classList.contains('file-item-download')) {
          await downloadFile(event)
        } else if (target.classList.contains('file-item-name') || target.classList.contains('chat-image')) {
          const item = findParent(target, '.msg-item')
          const message = this.messages.find(value => value.id === item.dataset.mid)
          await openFile(
            message.media,
            this.messages.filter(value => value.media).map(value => value.media)
          )
        }
      },
      async fetchMsg(append = false) {
        if (this.session?.type && !this.loading && this.page.page <= this.page.pages) {
          try {
            this.loading = true
            const { page, limit } = this.page
            const example = {
              'thread.id': this.session.thread.id,
              type: this.type === 'all' ? '' : this.type
            }

            if (this.query) {
              example.content = this.query
            }

            let res = await getMessage({
              current: page,
              size: limit,
              descs: ['createdAt'],
              example
            })
            res = res.data
            this.page.page++
            this.page.pages = res.data.totalPages
            if (append) {
              this.messages.push(...res.data.content)
            } else {
              this.messages = res.data.content
            }
          } catch (e) {
            console.error(e)
          }
          this.loading = false
        }
      },
      async reload() {
        this.page.page = 1
        this.page.pages = 1
        await this.fetchMsg()
      },
      async loadMore() {
        await this.fetchMsg(true)
      }
    }
  }
</script>

<style lang="scss">
  .msg-history-dialog {
    .msg-history {
      height: 420px;
    }

    .el-radio-button__inner {
      padding: 6px 20px;
    }

    .msg-item {
      display: flex;
      align-items: flex-start;
      padding: 14px 14px 0;
      line-height: 26px;
    }

    .sender-name {
      width: 50px;
      margin-right: 10px;
      text-align: right;
      text-overflow: ellipsis;
    }

    .send-time {
      flex-shrink: 0;
      width: 100px;
      color: gray;
      font-size: 12px;
      text-align: right;
      text-overflow: ellipsis;
    }

    .msg-content {
      flex: 1 1 auto;
      padding-right: 10px;
      color: black;
      white-space: normal;
      word-break: break-all;
    }

    .load-more {
      color: var(--color-primary);
      font-size: 0.8em;
      text-align: center;
      cursor: default;
    }

    .load-more-wrapper {
      padding-top: 20px;
      padding-bottom: 10px;
    }

    .el-dialog__body {
      padding: 0;
      background-color: #f6f8fa;
    }

    .msg-search-bar {
      @include flex-row;
      width: 80%;
      margin: 0 auto;
      padding: 10px;
    }

    .chat-message-content {
      @include flex-item;
      margin-left: 1px;
      color: black;
    }

    .msg-item-right {
      @include flex-item;
      @include flex-row;
      align-items: flex-start;
      padding-bottom: 14px;
      border-bottom: 1px solid #dcdcdc;
    }
  }
</style>
